package com.bdbit.ChargingStation.services;

import com.alibaba.fastjson.JSONObject;
import com.bdbit.ChargingStation.Enum.OrderStatus;
import com.bdbit.ChargingStation.entity.OrderEntity;
// import com.bdbit.ChargingStation.mapper.ChargingPileRepository;  // 注释掉这一行
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ChargingService {

    @Autowired
    private OrderService orderService;

    private final Map<String, ScheduledFuture<?>> chargingTasks = new ConcurrentHashMap<>();

    private int calculateChargingTime(OrderEntity order) {
        // 修改前：示例：100分=1元=60分钟
        // return (int) (order.getPrepayAmount().intValue() * 60 / 100.0);
        
        // 修改后：统一费率：1元 = 5分钟
        return (int) (order.getPrepayAmount().intValue() * 5);
    }

    public void handlePowerOff(String orderId) {
        OrderEntity order = orderService.getOrderByOrderNo(orderId);
        if (order == null || order.getStatus() != OrderStatus.CHARGING.getCode()) {
            return;
        }

        // 停止定时任务
        ScheduledFuture<?> future = chargingTasks.remove(orderId);
        if (future != null) {
            future.cancel(true);
        }

        // 计算剩余时间，部分退款
        int refundAmount = calculateRefundAmount(order);
        refundOrder(order, refundAmount);
    }

    private void refundOrder(OrderEntity order, int refundAmount) {
        // 调用支付平台退款接口
        // 更新订单状态为 REFUNDED
        order.setStatus(OrderStatus.REFUNDED.getCode());
        orderService.updateOrder(order);
    }

    private int calculateRefundAmount(OrderEntity order) {
        // 实际充电时间
        long actualSeconds = (System.currentTimeMillis() - order.getPaymentTime().getTime()) / 1000;
        int actualMinutes = (int) (actualSeconds / 60);

        // 原计划充电时间
        int plannedMinutes = calculateChargingTime(order);

        int remainingMinutes = Math.max(0, plannedMinutes - actualMinutes);
        return (int) ((double)remainingMinutes / 60.0 * order.getPrepayAmount().intValue());
    }
}
